package com.gzs.space.service.impl;

import com.gzs.space.entity.User;
import com.gzs.space.mapper.LoginMapper;
import com.gzs.space.response.CommonResponse;
import com.gzs.space.service.LoginService;
import com.gzs.space.utils.AESUtils;
import com.gzs.space.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author GZS
 * @date 2022年04月23日
 */
@Service
public class LoginServiceImpl implements LoginService {

	@Resource
	private LoginMapper loginMapper;


	@Value("${ase.secretKey}")
	private String secretKey;

	@Override
	@Transactional()
	public CommonResponse register(User user) {
		try {
			User userInfo = loginMapper.selectByUserName(user.getUserName());
			if(null != userInfo){
				return CommonResponse.fail("用户已存在");
			}
			user.setPassWord(AESUtils.aesEncrypt(user.getPassWord()));
			boolean flag = loginMapper.register(user);
			// if (flag){
			// 	//成功发送邮件
			// 	if (user.getEmail()!=null){
			// 		mailService.sendEmail(user.getEmail());
			// 	}
			// }
			return CommonResponse.ok("注册成功");
		} catch (Exception e) {
			e.printStackTrace();
			return CommonResponse.fail("注册失败");
		}
	}

	@Override
	public CommonResponse allUser() {

		List<User> users = loginMapper.allUser();
		return CommonResponse.ok(users);
	}


	//TODO  后续修改为将token存入redis，校验redis中是否有token
	@Override
	public CommonResponse login(User user) {
		try {
			user.setPassWord(AESUtils.aesEncrypt(user.getPassWord()));
			int count = loginMapper.selectCount(user);
			if (count!=1){
				return CommonResponse.fail("请检查账号密码是否有误！");
			}
			String token = JwtUtils.token(user.getUserName(), user.getPassWord());
			return CommonResponse.ok(token);
		} catch (Exception e) {
			e.printStackTrace();
			return CommonResponse.fail("登录失败");
		}
	}

	@Transactional
	@Override
	public CommonResponse edit(User user) {
		try {
			boolean flag = loginMapper.edit(user);
			return CommonResponse.ok("修改成功");
		} catch (Exception e) {
			e.printStackTrace();
			return CommonResponse.fail("修改失败");
		}
	}

}
